/*
 * Copyright 2006 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.util;

import java.net.*;
import java.io.*;
import java.util.*;

public class Util
{
    public static String XMLEscape ( String str )
    {
        if ( str != null )
        {
            str = Util.replace( str, "&", "&amp;" );
            str = Util.replace( str, "<", "&lt;" );
            str = Util.replace( str, ">", "&gt;" );
            str = Util.replace( str, "'", "&apos;" );
            str = Util.replace( str, "\"", "&quot;" );
        }

        return str;
    }

    public static String replace ( String str, String target, String rep )
    {
        return ( str != null ? str.replaceAll( target, rep ) : null );
    }

    public static String URLEncode ( String str )
    {
        String encoded = null;

        try
        {
            encoded = URLEncoder.encode( str, "UTF-8" );
        }
        catch ( UnsupportedEncodingException ex )
        {
            Log.getInstance().write( "Util: Exception urlencoding: " + str, ex );
        }

        return encoded;
    }

    public static String readStream ( InputStream stream, String charset ) throws IOException
    {
        return Util.readStream( new InputStreamReader( stream, charset ) );
    }

    public static String readStream ( InputStream stream ) throws IOException
    {
        //use the default character set
        return Util.readStream( new InputStreamReader( stream ) );
    }

    public static String readStream ( InputStreamReader reader ) throws IOException
    {
        StringBuffer db = new StringBuffer();
        
        BufferedReader bin = new BufferedReader( reader );

        String line = null;

        while ( ( line = bin.readLine() ) != null )
        {
            db.append( line ).append( "\n" );
        }
        
        bin.close();

        return db.toString();
    }

    public static boolean isNonEmpty ( String var )
    {
        return ( var != null && var.length() > 0 );
    }
}

